package com.scanner.hardware;

import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.scanner.barcodeservice.SerialPortService;
import com.scanner.base.BaseActivity;
import com.scanner.bean.MotoBarcode;
import com.scanner.hardware.adapter.MotoSigAdapter;
import com.scanner.hardware.db.helper.DaoHelper;
import com.scanner.ui.RecycleViewDivider;
import com.chad.library.adapter.base.BaseQuickAdapter;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class MotoSigCodeActivity extends BaseActivity {

    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_list)
    RecyclerView tvList;
    @BindView(R.id.ll_back)
    LinearLayout llBack;
    private List<MotoBarcode> motoBars;
    private DaoHelper daoHelper;
    private MotoSigAdapter adapter;

    @Override
    protected int getLayout() {
        return R.layout.activity_moto_sig_code;
    }

    @Override
    protected void initView() {
        tvTitle.setText(getString(R.string.motoloraone));
        llBack.setVisibility(View.VISIBLE);
        initData();
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this,
                LinearLayoutManager.VERTICAL, false);
        tvList.setLayoutManager(linearLayoutManager);
        tvList.addItemDecoration(new RecycleViewDivider(this, LinearLayoutManager.VERTICAL));
        adapter = new MotoSigAdapter(R.layout.item_motosiger_layout, motoBars);
        tvList.setAdapter(adapter);
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                int codeState = motoBars.get(position).getCodeState();
                if (codeState == 1) {//打开
                    motoBars.get(position).setCodeState(0);
                    sendBrocastUpdate(motoBars.get(position).getCodeCloseValue());
                } else if (codeState == 0) {//关闭
                    motoBars.get(position).setCodeState(1);
                    sendBrocastUpdate(motoBars.get(position).getCodeOpenValue());
                }
                daoHelper.updateSigCheck(motoBars.get(position));
                adapter.setData(position, motoBars.get(position));
            }
        });


    }

    private void sendBrocastUpdate(byte[] value) {
        Intent intent = new Intent(SerialPortService.BARCODEPORT_WRITEDATA_ACTION);
        intent.putExtra(SerialPortService.BARCODEPORT_WRITER_WXTAR_BYTRDATA, value);
        sendBroadcast(intent);
    }

    private void initData() {
        daoHelper = new DaoHelper(this);
        motoBars = daoHelper.getMotoBars();
    }

    @OnClick(R.id.ll_back)
    public void onViewClicked() {
        finish();
    }
}
